package cn.santi.service.impl;

import cn.santi.domain.OpenidCode;
import cn.santi.service.OpenidCodeService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Service
public class OpenidCodeServiceImpl implements OpenidCodeService {

    private final RestTemplate restTemplate;

    public OpenidCodeServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getOpenId(String appId, String secret, String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";
        url = url.replace("{appId}", appId).replace("{secret}", secret).replace("{code}", code);
        System.out.println("请求微信API的URL: " + url);

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            System.out.println("response::: " + response);
            System.out.println("微信API返回的状态码: " + response.getStatusCode());
            if (response.getStatusCode() == HttpStatus.OK) {
                // 尝试将响应体转换为OpenidCode对象
                OpenidCode authResponse = JSONObject.parseObject(response.getBody(), OpenidCode.class);
                System.out.println("session_key:::" + authResponse.getSession_key());
                System.out.println("openid:::" + authResponse.getOpenid());
                return authResponse.getOpenid();
            } else {
                // 打印错误信息
                System.err.println("微信API返回错误: " + response.getStatusCode() + ", 响应内容: " + response.getBody());
                return null;
            }
        } catch (RestClientException e) {
            System.err.println("调用微信API时发生错误: " + e.getMessage());
            return null;
        }
    }

}
